<script setup lang="ts" name="cardIndex">
import { defineAsyncComponent, ref, shallowRef, nextTick, onMounted, type Component } from 'vue'
import { useMainIndexStore } from '@/stores/mainIndexStore'
import { useCardStore } from '@/stores/cardStore'
import { useColumnStore } from '@/stores/columnStore'
import { useModalStore } from '@/stores/modalStore'
import type { CardData, ErrorData, ColumnsList } from '@/types/loginType'
import useFontImg from '@/utils/fontImg'

const { changeData } = useModalStore()
const { assignTitle } = useMainIndexStore()
const { imgArt } = useFontImg()
assignTitle(imgArt)
const menu = ref([
  { id: 0, msg: '文章' },
  { id: 1, msg: '专栏' }
])
const actived = ref(0)
const anyComponent = shallowRef<Component | null>(null)

async function menuClicked(id: number) {
  actived.value = id
  if (id === 0) {
    anyComponent.value = defineAsyncComponent(() => import('@/components/index/card/cardMsg.vue'))
    await nextTick()
    articleData()
  }
  if (id === 1) {
    anyComponent.value = defineAsyncComponent(() => import('@/components/index/card/columnMsg.vue'))
    await nextTick()
    columnsData()
  }
}

// 初始化cardOrigin
async function articleData() {
  const { articleData, assignCardData, assignCardOrigin } = useCardStore()
  const { status, data } = await articleData()
  if (status === 200) {
    ;(data as CardData[]).map((data) => {
      data.time = new Date(data.time).toLocaleString()
    })
    assignCardOrigin(data as CardData[])
    assignCardData(data as CardData[])
  } else {
    changeData({ status: status, data: { msg: (data as ErrorData).msg } })
  }
}

// 初始化 columnOrigin
async function columnsData() {
  const { columnsData, assignListOriginData, assignListData } = useColumnStore()
  const { status, data } = await columnsData()
  console.log(data)
  if (status === 200) {
    assignListOriginData(data as ColumnsList[])
    assignListData(data as ColumnsList[])
  } else {
    changeData({ status: status, data: { msg: (data as ErrorData).msg } })
  }
}

onMounted(() => {
  menuClicked(0)
})
</script>

<template>
  <ul class="menu">
    <li
      class="default-button"
      :class="{ active: actived === item.id }"
      v-for="item in menu"
      :key="item.id"
      @click="menuClicked(item.id)"
    >
      {{ item.msg }}
    </li>
  </ul>
  <div class="card">
    <component :is="anyComponent" />
  </div>
</template>

<style scoped lang="less">
.active {
  background-color: var(--color2);
  color: #fff;
}
.menu {
  display: flex;
  list-style: none;
  border-bottom: 2px dashed var(--color2);
  > li {
    cursor: pointer;
    padding: 10px;
    border-radius: var(--radius) var(--radius) 0 0;
    color: var(--color3);
  }
}
.card {
  padding-top: 6px;
}
</style>
